package org.example.lotterysystem.common.domain;

import lombok.Data;
import org.example.lotterysystem.common.errorcode.ErrorCode;
import org.example.lotterysystem.common.errorcode.GlobalErrorCodeConstants;

import java.io.Serializable;

@Data
public class Result <T> implements Serializable {
    //状态码
    private Integer code;
    //状态码解释
    private String msg;
    //返回数据
    private T data;

    public static <T> Result<T> success() {
        //执行成功，但不返回数据
        return assembleResult(null, GlobalErrorCodeConstants.SUCCESS);
    }

    public static <T> Result<T> success(T data) {
        //执行成功，但返回数据
        return assembleResult(data, GlobalErrorCodeConstants.SUCCESS);
    }

    public static <T> Result<T> fail() {
        //执行失败
        return assembleResult(null, GlobalErrorCodeConstants.FAILED);
    }

    //指定状态码和返回信息
    public static <T> Result<T> fail(Integer code, String msg) {
        return assembleResult(code, msg, null);
    }

    //指定错误码
    public static <T> Result<T> fail(ErrorCode errorCode) {
        return assembleResult(null, errorCode);
    }

    private static <T> Result<T> assembleResult(T data, ErrorCode errorCode) {
        Result<T> result = new Result<>();
        result.setCode(errorCode.getCode());
        result.setData(data);
        result.setMsg(errorCode.getMsg());
        return result;
    }

    private static <T> Result<T> assembleResult(Integer code, String msg, T data) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setData(data);
        result.setMsg(msg);
        return result;
    }
}
